(function (global) {

    //获取cookie对象，以对象表示
    function getCookiesObj()
    {
        let cookies  = {}
        if(document.cookie)
        {
            // 获取所有cookie字符串
            let obj = document.cookie.split(';')
            obj.forEach((item) =>{
                // 通过字符串查找对应索引值
                let index = item.indexOf('=');
                // substring字符串的截取, trim去除两端空格
                let name = item.substring(0, index).trim();
                let value = item.substring(index + 1).trim();
                // decodeURIComponent() 方法用于解码由 encodeURIComponent 方法或者其他类似方法编码的部分统一资源标识符（URI）。
                cookies[decodeURIComponent(name)] = decodeURIComponent(value);
            })
        }

        return cookies;
    }

    //设置cookie
    function set(name, value, opts)
    {
        if(name && value)
        {
            let cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

            if(opts)
            {
                if(opts.maxAge){
                    cookie += '; max-age=' + opts.maxAge; 
                }
                if(opts.path){
                    cookie += '; path=' + opts.path;
                }
                if(opts.domain){
                    cookie += '; domain=' + opts.domain;
                }
                if(opts.secure){
                    cookie += '; secure';
                }
            }

            document.cookie = cookie;
        }
    }

    //获取单个cookie
    function get(name)
    {
        return getCookiesObj()[name] || '';
    }

    // 获取所有的cookie
    function getCookies()
    {
        return getCookiesObj();
    }

    // 删除单个cookie
    function remove(name)
    {
        if(getCookiesObj()[name])
        {
            document.cookie = name + '=; max-age=0'
        }
    }

    // 删除所有cookie
    function clear()
    {
        let cookies  = getCookiesObj()
        if(JSON.stringify(cookies) != '{}')
        {
            for(let item in cookies)
            {
                document.cookie = item + '=; max-age=0'
            }
        }
    }

    // 解决命名冲突
    function noConflict(name)
    {
        if(name && typeof name == 'string')
        {
            global[name] = global.cookie;
            delete window['cookie'];
        }

        return window[name];
    }

    global.cookie = {
        'set': set,
        'get': get,
        'getCookies': getCookies,
        'remove': remove,
        'clear': clear,
        'noConflict': noConflict
    }
})(window);